package com.jc.service.common.interceptor;

import com.jc.service.common.config.Config;
import com.jc.service.common.exception.ServiceException;
import com.jc.service.common.model.LoginUser;
import com.jc.service.common.model.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 租户ID验证拦截器
 * 用于检查API路径中的tenantId与token中的tenantId是否一致
 */
@Component
public class TenantIdValidationInterceptor implements HandlerInterceptor {

    private final Pattern tenantIdPattern;
    private final Logger logger = LoggerFactory.getLogger(TenantIdValidationInterceptor.class);
    
    public TenantIdValidationInterceptor(Config interceptorConfig) {
        // 从配置文件中获取正则表达式
        this.tenantIdPattern = Pattern.compile(
            interceptorConfig.getTenantIdValidation().getPathPattern()
        );
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求路径
        String requestPath = request.getRequestURI();
        
        // 尝试从路径中提取tenantId
        Matcher matcher = tenantIdPattern.matcher(requestPath);
        if (matcher.find()) {
            String pathTenantId = matcher.group(1);
            logger.debug("requestPath tenantId :{}",pathTenantId);
            // 从上下文中获取当前登录用户
            LoginUser currentUser = UserContext.getUser();
            if (currentUser == null) {
                throw new ServiceException(HttpStatus.UNAUTHORIZED.value(), "未获取到用户认证信息");
            }
            
            // 获取token中的tenantId
            String tokenTenantId = currentUser.getTenantId();
            
            // 比较路径中的tenantId和token中的tenantId
            if (!pathTenantId.equals(tokenTenantId)) {
                throw new ServiceException(HttpStatus.FORBIDDEN.value(), 
                    "访问被拒绝：路径中的租户ID与您的认证信息不匹配");
            }
        }
        
        return true;
    }
}